package com.designpatterns.proxy.myproxy;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader {

    private File baseDir;

    public MyClassLoader() {
        String basePath =ClassLoader.getSystemResource("").getPath();
        this.baseDir = new File(basePath);
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (baseDir != null) {
            File classFile = new File(baseDir,name+".class");
            if (classFile.exists()) {
                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) !=-1) {
                        out.write(buff,0,len);
                    }
                    //换成一个Class并初始化
                    return defineClass(name,out.toByteArray(),0,out.size());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != in) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    classFile.delete();
                }
            }
        }

        return super.findClass(name);
    }
}
